import { Vector2D } from './Vector2D.js'

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
ctx.translate(0, canvas.height)
ctx.scale(1, -1)

/**
 * 
 * @param {Vector2D} Q 
 * @param {Vector2D} R 
 * @param {Vector2D} P 
 */
function draw(Q, R, P) {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  const arr = [{
    vec: Q,
    text: 'Q'
  }, {
    vec: R,
    text: 'R'
  }, {
    vec: P,
    text: 'P'
  }]
  ctx.setLineDash([])
  arr.forEach(({ vec, text }) => {
    // 画点
    ctx.fillStyle = '#ff0000'
    ctx.beginPath()
    ctx.arc(vec.x, vec.y, 2, 0, Math.PI * 2)
    ctx.closePath()
    ctx.fill()

    ctx.scale(1, -1)
    ctx.fillText(text, vec.x + 5, -vec.y - 5)
    ctx.scale(1, -1)
  })

  ctx.moveTo(...Q)
  ctx.lineTo(...R)
  ctx.stroke()

  // 绘制垂线
  const QR = R.copy().sub(Q)
  const QP = P.copy().sub(Q)

  const len = QR.cross(QP) / QR.len
  const cos = QR.copy().normalize().dot(QP.copy().normalize())
  const QT = QR.copy().normalize().scale(QP.len * cos)
  const T = Q.copy().add(QT)
  ctx.moveTo(...P)
  ctx.lineTo(...T)
  ctx.stroke()

  // 绘制点QT
  ctx.setLineDash([5, 5])
  ctx.moveTo(...Q)
  ctx.lineTo(...T)
  ctx.stroke()
}

let curPoint = null

canvas.addEventListener('mousedown', e => {
  // 判断当前最近的点
  // 范围是20
  const { offsetX, offsetY } = e
  const x = offsetX
  const y = canvas.height - offsetY

  const point = [Q, R, P].map(vec => ({
    len: vec.copy().sub(new Vector2D(x, y)).len,
    point: vec
  }))
    .sort((a, b) => a.len - b.len)[0]

  // 
  if (point.len < 20) {
    curPoint = point.point
  }
})

canvas.addEventListener('mousemove', e => {
  if (curPoint) {
    const { offsetX, offsetY } = e
    const x = offsetX
    const y = canvas.height - offsetY

    curPoint.x = x
    curPoint.y = y

    draw(Q, R, P)
  }
})

canvas.addEventListener('mouseup', e => {
  curPoint = false
})

const Q = new Vector2D(100, 100)
const R = new Vector2D(150, 200)
const P = new Vector2D(30, 250)

draw(Q, R, P)